package com.huawei.spare.part.replace;

import com.huawei.spare.part.replace.utils.SimplePTY;
import java.io.IOException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import net.schmizz.sshj.SSHClient;
import net.sf.expectit.MultiResult;
import net.sf.expectit.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.huawei.spare.part.replace.Constants.ResponseAskContinue;
import static com.huawei.spare.part.replace.Constants.ResponseNotExecuted;
import static com.huawei.spare.part.replace.Constants.ResponseSuccess;
import static com.huawei.spare.part.replace.Constants.ShellReady;
import static com.huawei.spare.part.replace.Constants.SwitchPowerOff;
import static net.sf.expectit.matcher.Matchers.anyOf;
import static net.sf.expectit.matcher.Matchers.contains;

public class Commands {

  private static final Logger log = LoggerFactory.getLogger(Commands.class);

  /**
   * power off switch
   *
   * @throws IOException
   * @throws InterruptedException
   */
  public static CommandResult powerOffSwitch(SSHClient ssh, int slot, int fruId)
      throws IOException, InterruptedException {
    SimplePTY PTY = SimplePTY.allocate(ssh);
    PTY.expect(contains(ShellReady));
    PTY.sendLine(String.format(SwitchPowerOff, slot, fruId));
    PTY.expect(10, contains(ResponseAskContinue));
    PTY.sendLine("Y");
    final MultiResult multiResult = PTY.expect(10, anyOf(contains(ResponseSuccess), contains(ResponseNotExecuted)));
    PTY.closeSession();
    if (multiResult.getResults().get(0).isSuccessful()) {
      return new CommandResult(true, multiResult.getResults().get(0));
    } else {
      return new CommandResult(false, multiResult.getResults().get(1));
    }
  }

  @Data
  @AllArgsConstructor
  @NoArgsConstructor
  public static class CommandResult {
    boolean success;
    Result result;
  }
}
